import React, { useEffect, useState, useContext } from 'react'
import { Text, View, Button, TouchableOpacity, SafeAreaView, TextInput, StyleSheet, Dimensions, Alert } from 'react-native'
import { useNavigation } from '@react-navigation/native'
import Icon from 'react-native-vector-icons/FontAwesome';

import useApi from '../api/api.js';
import { AuthContext } from '../components/AuthContext';

const { width: screenWidth, height: screenHeight } = Dimensions.get('window');

const BASE_URL = 'http://124.222.104.145:8003';   //后端提供的基础URL

const LoginPage = () => {
    const navigation = useNavigation();
    const [keyVisible, setKeyVisible] = useState(false);
    const [ifHaveAccount, setIfHaveAccount] = useState(true);

    const [loading, setLoading] = useState(false);

    const [loginUsername, setLoginUsername] = useState('');
    const [loginPassword, setLoginPassword] = useState('');

    const [registerUsername, setRegisterUsername] = useState('');
    const [registerPassword, setRegisterPassword] = useState('');
    const [registerPasswordConfirm, setRegisterPasswordConfirm] = useState('');
    const [registerEmail, setRegisterEmail] = useState('');
    const [verificationCode, setVerificationCode] = useState('');

    const [verificationTimeCountdown, setVerificationTimeCountdown] = useState(0);

    const { signIn } = useContext(AuthContext);

    const handleLogin = async () => {
        // 添加空值验证
        if (!loginUsername.trim() || !loginPassword.trim()) {
            Alert.alert('错误', '用户名和密码不能为空');
            return;
        }
        setLoading(true);
        try {
            const response = await fetch(`${BASE_URL}/user/login/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: loginUsername,
                    password: loginPassword
                })
            });

            if (!response.ok) {
                console.log('登录wrong:', response.status, response.success);
                const errorData = await response.json();
                console.log('登录错误信息:', errorData);
                throw new Error(errorData.message || '登录失败');
            }

            const result = await response.json();
            console.log('登录成功:', result);

            // 新增：调用上下文登录方法
            await signIn(result.token.access);

            Alert.alert('登录成功', result.message?.toString() || '登录成功');

        } catch (error) {
            Alert.alert('登录失败', error.message);
            // setLoading(false);
        } finally {
            setLoading(false);

            navigation.goBack();
        }
    }

    const handleRegister = async () => {
        // 添加注册表单验证
        if (!registerUsername.trim() ||
            !registerPassword.trim() ||
            !registerPasswordConfirm.trim() ||
            !registerEmail.trim() ||
            !verificationCode.trim()) {
            Alert.alert('错误', '所有字段必须填写且不得有空格');
            return;
        }

        if (registerPassword !== registerPasswordConfirm) {
            Alert.alert('错误', '两次输入的密码不一致');
            return;
        }

        setLoading(true);
        try {
            const response = await fetch(`${BASE_URL}/user/register/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: registerUsername,
                    email: registerEmail,
                    password: registerPassword,
                    password_confirm: registerPasswordConfirm,
                    verification_code: verificationCode
                })
            });

            const result = await response.json(); // 修复2：避免重复解析响应
            console.log('注册结果:', result); // 修复3：打印完整的结果

            if (!response.ok) {
                throw new Error(result.message || '注册失败');
            }

            console.log('注册成功:', result);
            Alert.alert('注册成功', result.message?.toString() || '注册成功');

        } catch (error) {
            Alert.alert('注册失败', error.message);
            // setLoading(false);
        } finally {
            setLoading(false);
        }
    }

    const handleSendVerificationCode = async () => {
        // 添加邮箱验证
        if (!registerEmail.trim()) {
            Alert.alert('错误', '请输入邮箱地址');
            return;
        }
        // 在发送验证码时也检查邮箱格式
        if (!registerEmail.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
            Alert.alert('错误', '请输入有效的邮箱地址');
            return;
        }
        setVerificationTimeCountdown(60);
        try {
            const response = await fetch(`${BASE_URL}/user/send-verification-code/`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: registerUsername,
                    email: registerEmail,
                    action: "register",
                })
            });

            const result = await response.json(); // 修复2：避免重复解析响应
            console.log('响应结果:', result); // 修复3：打印完整的结果

            if (!response.ok) {
                throw new Error(result.message || '发送失败');
            }

            Alert.alert('发送成功', result.message?.toString() || '发送成功');

        } catch (error) {
            Alert.alert('失败', error.message);
            // setLoading(false);
        } finally {
            // setLoading(false);
        }
    }

    useEffect(() => {
        if (verificationTimeCountdown > 0) {
            const timer = setTimeout(() => {
                setVerificationTimeCountdown(verificationTimeCountdown - 1);
            }, 1000);
            return () => clearTimeout(timer);
        }
    })

    return (
        //子路由内页面
        // 修改主容器样式
        <SafeAreaView style={{
            flex: 1,
            justifyContent: 'center', // 添加垂直居中
        }}>
            {/* 顶部返回条 */}
            <View
                style={{
                    paddingBlock: 12,
                    paddingHorizontal: 30,
                    paddingTop: 30,
                    paddingRight: 50,
                    backgroundColor: "rgb(230, 230, 230)",
                    position: 'absolute',  // 修改为绝对定位
                    top: 0,
                    left: 0,
                    right: 0,
                }}>
                <View style={{ flexDirection: "row", justifyContent: "space-between" }}>
                    <TouchableOpacity onPress={() => navigation.goBack()}>
                        <Icon name="angle-left" size={30} color="#000" />
                    </TouchableOpacity>
                </View>
            </View>

            {ifHaveAccount ?

                <View style={{
                    flex: 1,
                    alignItems: 'center',
                    justifyContent: 'center', // 添加垂直居中
                    paddingTop: 60, // 为顶部导航栏留出空间
                }} >
                    <View style={{ height: 200 }} />
                    <View style={{ alignItems: 'center', justifyContent: 'center' }}>
                        <Text style={{ fontSize: 30, fontWeight: "bold" }}>欢迎登录</Text>
                    </View>
                    <View style={{ height: 60 }} />

                    <View style={{ flex: 1, }}>
                        <View style={{ flexDirection: "row", alignItems: 'center', marginBottom: 20 }}>
                            <TextInput
                                value={loginUsername}
                                onChangeText={(text) => setLoginUsername(text)}
                                type="text"
                                placeholder="用户名"
                                style={[
                                    styles.inputBox,
                                    { paddingRight: 60 }
                                ]}
                            />
                            <Text style={{
                                fontSize: 30,
                                fontWeight: 'light',
                                position: 'absolute',
                                right: 40,
                                bottom: 0,
                                color: 'rgba(122, 122, 122, 0.5)'
                            }}>|</Text>
                            <Icon
                                name="user"
                                size={20}
                                color="#000"
                                style={{
                                    color: "rgba(100, 100, 100, 0.8)",
                                    position: 'absolute',
                                    right: 15,
                                    top: 8
                                }}
                            />
                        </View>
                        <View style={{ flexDirection: "row", alignItems: 'center', marginBottom: 20 }}>
                            <TextInput
                                value={loginPassword}
                                onChangeText={(text) => setLoginPassword(text)}
                                type="password"
                                placeholder="密码"
                                style={[
                                    styles.inputBox,
                                    { paddingRight: 60 }
                                ]}
                                secureTextEntry={!keyVisible}
                            />
                            <Text style={{
                                fontSize: 30,
                                fontWeight: 'light',
                                position: 'absolute',
                                right: 40,
                                bottom: 0,
                                color: 'rgba(122, 122, 122, 0.5)'
                            }}>|</Text>
                            <TouchableOpacity onPress={() => setKeyVisible(!keyVisible)}>
                                {!keyVisible ?
                                    <Icon
                                        name="lock"
                                        size={20}
                                        color="#000"
                                        style={{
                                            color: "rgba(100, 100, 100, 0.8)",
                                            position: 'absolute',
                                            right: 15,
                                            top: -8
                                        }}
                                    />
                                    :
                                    <Icon
                                        name="unlock"
                                        size={20}
                                        color="#000"
                                        style={{
                                            color: "rgba(100, 100, 100, 0.8)",
                                            position: 'absolute',
                                            right: 12,
                                            top: -8
                                        }}
                                    />
                                }
                            </TouchableOpacity>

                        </View>

                        {!loading ?
                            <TouchableOpacity style={{
                                backgroundColor: 'rgb(107, 142, 195)',
                                width: screenWidth * 0.7,
                                alignItems: 'center',
                                justifyContent: 'center',
                                marginBottom: 20,
                                height: 37,
                                borderRadius: 8,
                            }}
                                onPress={() => handleLogin()}
                            >
                                <Text style={{
                                    fontSize: 16,
                                    fontWeight: "bold",
                                    color: "rgb(255, 255, 255)"
                                }}>登录</Text>
                            </TouchableOpacity>

                            :

                            <View style={{
                                backgroundColor: 'rgba(255, 255, 255, 0)',
                                width: screenWidth * 0.7,
                                alignItems: 'center',
                                justifyContent: 'center',
                                marginBottom: 20,
                                height: 37,
                                borderRadius: 8,
                            }}
                                onPress={() => handleLogin()}
                            >
                                <Text style={{
                                    fontSize: 16,
                                    fontWeight: "bold",
                                    color: "rgb(0, 0, 0)"
                                }}>登录中...</Text>
                            </View>
                        }

                        <TouchableOpacity onPress={() => setIfHaveAccount(!ifHaveAccount)} style={{
                            flexDirection: "row",
                            alignItems: 'center',
                            justifyContent: 'center',
                            marginBottom: 20,
                            height: 37,
                            borderRadius: 8,
                        }}>
                            <Text style={{
                                fontSize: 14,
                                fontWeight: "bold",
                                color: "rgb(107, 142, 195)"
                            }}>暂无账号，前往注册</Text>
                        </TouchableOpacity>

                        <View style={{ flex: 1 }} />

                        <TouchableOpacity
                            onPress={() => navigation.navigate('ResetPassword')}
                            style={{
                                flexDirection: "row",
                                alignItems: 'center',
                                justifyContent: 'center',
                                marginBottom: 40,
                                height: 37,
                                borderRadius: 8,
                            }}
                        >
                            <Text style={{
                                fontSize: 14,
                                fontWeight: "bold",
                                color: "rgb(107, 142, 195)"
                            }}>忘记密码？</Text>
                        </TouchableOpacity>
                    </View>
                </View>

                :

                <View style={{ flex: 1, alignItems: 'center', }} >
                    <View style={{ height: 150 }} />
                    <View style={{ alignItems: 'center', justifyContent: 'center' }}>
                        <Text style={{ fontSize: 30, fontWeight: "bold" }}>欢迎注册</Text>
                    </View>
                    <View style={{ height: 60 }} />

                    <View style={{ flex: 1, }}>
                        <View style={{ flexDirection: "row", alignItems: 'center', marginBottom: 20 }}>
                            <TextInput
                                value={registerUsername}
                                onChangeText={(text) => setRegisterUsername(text)}
                                type="text"
                                placeholder="用户名"
                                style={[
                                    styles.inputBox,
                                    { paddingRight: 60 }
                                ]}
                            />
                            <Text style={{
                                fontSize: 30,
                                fontWeight: 'light',
                                position: 'absolute',
                                right: 40,
                                bottom: 0,
                                color: 'rgba(122, 122, 122, 0.5)'
                            }}>|</Text>
                            <Icon
                                name="user"
                                size={20}
                                color="#000"
                                style={{
                                    color: "rgba(100, 100, 100, 0.8)",
                                    position: 'absolute',
                                    right: 15,
                                    top: 8
                                }}
                            />
                        </View>

                        <View style={{ flexDirection: "row", alignItems: 'center', marginBottom: 20 }}>
                            <TextInput
                                value={registerPassword}
                                onChangeText={(text) => setRegisterPassword(text)}
                                type="password"
                                placeholder="密码"
                                style={[styles.inputBox, { paddingRight: 60 }]}
                                secureTextEntry={!keyVisible}
                            />
                            <Text style={{ fontSize: 30, fontWeight: 'light', position: 'absolute', right: 40, bottom: 0, color: 'rgba(122, 122, 122, 0.5)' }}>|</Text>
                            <TouchableOpacity onPress={() => setKeyVisible(!keyVisible)}>
                                {/* <Icon name={!keyVisible? "lock" : "unlock"} size={20} color="#000" style={{ position: 'absolute', right: 15, top: -8 }}/> */}
                                {!keyVisible ?
                                    <Icon
                                        name="lock"
                                        size={20}
                                        color="#000"
                                        style={{
                                            color: "rgba(100, 100, 100, 0.8)",
                                            position: 'absolute',
                                            right: 15,
                                            top: -8
                                        }}
                                    />
                                    :
                                    <Icon
                                        name="unlock"
                                        size={20}
                                        color="#000"
                                        style={{
                                            color: "rgba(100, 100, 100, 0.8)",
                                            position: 'absolute',
                                            right: 12,
                                            top: -8
                                        }}
                                    />
                                }
                            </TouchableOpacity>

                        </View>

                        <View style={{ flexDirection: "row", alignItems: 'center', marginBottom: 20 }}>
                            <TextInput
                                value={registerPasswordConfirm}
                                onChangeText={(text) => setRegisterPasswordConfirm(text)}
                                type="password"
                                placeholder="重复密码"
                                style={[styles.inputBox, { paddingRight: 60 }]}
                                secureTextEntry={!keyVisible}
                            />
                            <Text style={{ fontSize: 30, fontWeight: 'light', position: 'absolute', right: 40, bottom: 0, color: 'rgba(122, 122, 122, 0.5)' }}>|</Text>
                            <TouchableOpacity onPress={() => setKeyVisible(!keyVisible)}>
                                {/* <Icon name={!keyVisible? "lock" : "unlock"} size={20} color="#000" style={{ position: 'absolute', right: 15, top: -8 }}/> */}
                                {!keyVisible ?
                                    <Icon
                                        name="lock"
                                        size={20}
                                        color="#000"
                                        style={{
                                            color: "rgba(100, 100, 100, 0.8)",
                                            position: 'absolute',
                                            right: 15,
                                            top: -8
                                        }}
                                    />
                                    :
                                    <Icon
                                        name="unlock"
                                        size={20}
                                        color="#000"
                                        style={{
                                            color: "rgba(100, 100, 100, 0.8)",
                                            position: 'absolute',
                                            right: 12,
                                            top: -8
                                        }}
                                    />
                                }
                            </TouchableOpacity>

                        </View>

                        <View style={{ flexDirection: "row", alignItems: 'center', marginBottom: 20 }}>
                            <TextInput
                                value={registerEmail}
                                onChangeText={(text) => setRegisterEmail(text)}
                                type="email"
                                placeholder="邮箱"
                                style={[
                                    styles.inputBox,
                                    { paddingRight: 60 }
                                ]}
                            />
                            <Text style={{
                                fontSize: 30,
                                fontWeight: 'light',
                                position: 'absolute',
                                right: 40,
                                bottom: 0,
                                color: 'rgba(122, 122, 122, 0.5)'
                            }}>|</Text>
                            <Icon
                                name="envelope"
                                size={20}
                                color="#000"
                                style={{
                                    color: "rgba(100, 100, 100, 0.8)",
                                    position: 'absolute',
                                    right: 11,
                                    top: 8
                                }}
                            />
                        </View>

                        <View style={{ flexDirection: "row", alignItems: 'center', marginBottom: 20 }}>
                            <TextInput
                                value={verificationCode}
                                onChangeText={(text) => setVerificationCode(text)}
                                type="text"
                                placeholder="验证码"
                                style={[
                                    styles.inputBox,
                                    { paddingRight: 100 }
                                ]}
                                maxLength={6}          // 新增长度限制
                                keyboardType="number-pad"  // 推荐添加数字键盘
                            />
                            <View style={{
                                fontSize: 30,
                                fontWeight: 'light',
                                position: 'absolute',
                                right: 0,
                                bottom: 0,
                                color: 'rgba(122, 122, 122, 0.5)'
                            }}>
                                {verificationTimeCountdown > 0 ?

                                    <View style={{
                                        backgroundColor: 'rgb(107, 142, 195)',
                                        width: screenWidth * 0.17,
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        // marginBottom: 20,
                                        height: 35,
                                        borderRadius: 8,
                                    }} >
                                        <Text style={{ fontSize: 16, color: "rgb(255, 255, 255)", fontWeight: 'bold' }}>
                                            {verificationTimeCountdown}s
                                        </Text>
                                    </View>

                                    :

                                    <TouchableOpacity style={{
                                        backgroundColor: 'rgb(107, 142, 195)',
                                        width: screenWidth * 0.17,
                                        alignItems: 'center',
                                        justifyContent: 'center',
                                        // marginBottom: 20,
                                        height: 35,
                                        borderRadius: 8,
                                    }}
                                        onPress={() => handleSendVerificationCode()}
                                    >
                                        <Text style={{
                                            fontSize: 16,
                                            fontWeight: "bold",
                                            color: "rgb(255, 255, 255)"
                                        }}
                                        >获取</Text>
                                    </TouchableOpacity>

                                }

                            </View>

                        </View>

                        {!loading ?
                            <TouchableOpacity style={{
                                backgroundColor: 'rgb(107, 142, 195)',
                                width: screenWidth * 0.7,
                                alignItems: 'center',
                                justifyContent: 'center',
                                marginBottom: 20,
                                height: 37,
                                borderRadius: 8,
                            }}
                                onPress={() => handleRegister()}
                            >
                                <Text style={{
                                    fontSize: 16,
                                    fontWeight: "bold",
                                    color: "rgb(255, 255, 255)"
                                }}
                                >注册</Text>
                            </TouchableOpacity>
                            :
                            <TouchableOpacity style={{
                                backgroundColor: 'rgba(107, 142, 195, 0)',
                                width: screenWidth * 0.7,
                                alignItems: 'center',
                                justifyContent: 'center',
                                marginBottom: 20,
                                height: 37,
                                borderRadius: 8,
                            }}
                                onPress={() => handleRegister()}
                            >
                                <Text style={{
                                    fontSize: 16,
                                    fontWeight: "bold",
                                    color: "rgb(0, 0, 0)"
                                }}
                                >注册中...</Text>
                            </TouchableOpacity>
                        }

                        <TouchableOpacity onPress={() => setIfHaveAccount(!ifHaveAccount)} style={{
                            flexDirection: "row",
                            alignItems: 'center',
                            justifyContent: 'center',
                            marginBottom: 20,
                            height: 37,
                            borderRadius: 8,
                        }}>
                            <Text style={{ fontSize: 14, fontWeight: "bold", color: "rgb(107, 142, 195)" }}>已有账号，前往登录</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            }

        </SafeAreaView>
    )
}

const styles = StyleSheet.create({
    inputBox: {
        backgroundColor: 'rgba(173, 173, 173, 0.42)',
        borderRadius: 8,
        paddingHorizontal: 20,
        paddingVertical: 8, // 增加垂直内边距
        height: 36,
        width: screenWidth * 0.7,
        fontSize: 15, // 稍微调小字体
        fontWeight: 'normal',
        textAlignVertical: 'center',
        includeFontPadding: false,
    },
    forgotPassword: {
        alignSelf: 'flex-end',
        marginTop: 10,
        marginRight: screenWidth * 0.15,
        marginBottom: 10,
    },
    forgotPasswordText: {
        color: '#366',
        fontSize: 14,
    }
});

export default LoginPage


